package com.itx.gatewayx.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * HTTP工具类
 * 
 * @author itx
 */
@Slf4j
public class HttpUtils {

    /**
     * 发送GET请求
     * 
     * @param apiUrl 请求URL
     * @param params 请求参数
     * @return 响应结果
     * @throws Exception 异常
     */
    public static String doGet(String apiUrl, Map<String, String> params) throws Exception {
        URL url = new URL(String.format("%s?%s", apiUrl, formatParams(params)));
        log.debug("请求URL: {}", url);
        
        try (BufferedReader in = new BufferedReader(
                new InputStreamReader(url.openConnection().getInputStream(), StandardCharsets.UTF_8))) {
            
            return in.lines().collect(Collectors.joining());
        }
    }
    
    /**
     * 格式化请求参数
     * 
     * @param params 参数Map
     * @return 格式化后的参数字符串
     */
    private static String formatParams(Map<String, String> params) {
        if (params == null || params.isEmpty()) {
            return "";
        }
        
        return params.entrySet().stream()
                .filter(entry -> StringUtils.hasLength(entry.getValue()))
                .map(entry -> {
                    try {
                        return entry.getKey() + "=" + 
                                URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8.toString());
                    } catch (Exception e) {
                        log.error("参数编码失败", e);
                        return entry.getKey() + "=" + entry.getValue();
                    }
                })
                .collect(Collectors.joining("&"));
    }
} 